from rest_framework.viewsets import ModelViewSet

from questions.qaSerialzers import *
from users.models import *
from rest_framework_jwt.utils import jwt_decode_handler
from rest_framework.response import Response
from django.db import transaction
from django_redis import get_redis_connection

# Create your views here.


class LabelallViewSet(ModelViewSet):
    """返回所有标签 难点 中间表的查询"""
    queryset = Label.objects.all()
    serializer_class = LabelSerializer

    def retrieve(self, request, *args, **kwargs):
        """返回用户关注的标签"""
        # user1 = request.user.id
        token = request.META.get("HTTP_AUTHORIZATION")[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user.get("user_id")
        user = User.objects.get(id=user_id)
        labels = user.labels.all()
        serializer = LabelSerializer(labels, many=True)
        return Response(serializer.data)

    def retrieve_data(self, request, *args, **kwargs):
        """返回标签内容"""
        id = kwargs.get("id")

        try:
            labels = self.get_queryset().get(id=id)
        except Exception as e:
            return Response({'message': '查询失败', 'success': False})
        serializer = LabelSerializer(labels)
        return Response(serializer.data)

    def user_focusin_labels(self, request, *args, **kwargs):
        """用户关注标签"""
        user_id = request.user.id
        id = kwargs.get("id")  # 标签ID
        try:
            labels = self.get_queryset().get(id=id)  # 查询出指定一个标签
        except Exception as e:
            return Response({'message': '关注失败', 'success': False})
        labels.users.add(user_id)  # 添加到用户关注表中
        return Response({'success': True, 'message': '关注成功'})
        pass

    def user_focusout_labels(self, request, *args, **kwargs):
        """用户取消关注标签"""
        user_id = request.user.id
        id = kwargs.get("id")  # 标签ID
        try:
            labels = self.get_queryset().get(id=id)  # 查询出指定一个标签
        except Exception as e:
            return Response({'success': False, 'message': '关注失败'})
        labels.users.remove(user_id)  # 删除用户关注标签
        return Response({'success': True, 'message': '关注成功'})
        pass


class QuestionViewSet(ModelViewSet):
    """所有问题视图集"""
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

    def list2(self, request, *args, **kwargs):
        """等待回答   /questions/{id}/label/wait/"""
        id = kwargs.get("id")
        if id == "-1":
            data = self.get_queryset().all().order_by("-createtime")
            serializer = QuestionSerializer(data, many=True)
            return Response(serializer.data)
        else:
            question = Question.objects.filter(labels=id).order_by("-createtime")
            serializer = QuestionSerializer(question, many=True)
            return Response(serializer.data)
        pass

    def list1(self, request, *args, **kwargs):
        """最热回答  questions/-1/label/hot/"""
        id = kwargs.get("id")
        if id == "-1":
            data = self.get_queryset().all().order_by("-reply")
            serializer = QuestionSerializer(data, many=True)
            return Response(serializer.data)
        else:
            question = Question.objects.filter(labels=id).order_by("-reply")
            serializer = QuestionSerializer(question, many=True)
            return Response(serializer.data)
        pass

    def list(self, request, *args, **kwargs):
        """最新回答的问题"""
        id = kwargs.get("id")
        if id == "-1":
            data = self.get_queryset().all().order_by("-updatetime")
            serializer = QuestionSerializer(data, many=True)
            return Response(serializer.data)
        else:
            try:
                question = Question.objects.filter(labels=id).order_by("-updatetime")
            except Exception as e:
                return Response({"message": "数据查询失败...", "success": False})
            serializer = QuestionSerializer(question, many=True)
            return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        """发布问题"""
        token = request.META.get("HTTP_AUTHORIZATION")[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user.get("user_id")

        content = request.data.get("content")
        labels = request.data.get("labels")
        title = request.data.get("title")
        with transaction.atomic():  # 打开事物
            save_id = transaction.savepoint()  # 创建事物
            try:
                qa = Question.objects.create(content=content,
                                             title=title,
                                             user_id=user_id)
                for label in labels:
                    qa.labels.add(label)

            except Exception as e:
                transaction.savepoint_rollback(save_id)  # 回滚事物
                print(e)
                return Response({"message": "数据处理失败...", "success": False})
        transaction.savepoint_commit(save_id)  # 执行成功
        return Response({"message": "发布成功...", "success": True})


class QuestionsModelViewSet(ModelViewSet):
    """问题详情界面"""
    queryset = Question.objects.all()
    serializer_class = QuestionsSerializer

    def retrieve(self, request, *args, **kwargs):
        """某一个问题详情"""
        id = kwargs.get("id")
        data = self.get_queryset().get(id=id)
        data.visits= data.visits + 1
        data.save()
        serializer = QuestionsSerializer(data)
        return Response(serializer.data)

    def update_useful_count(self, request, *args, **kwargs):
        """问题有用，修改有用数"""
        redis_conn = get_redis_connection("question")
        id = kwargs.get("id")  # id 表示问题外键的id
        token = request.META.get("HTTP_AUTHORIZATION")[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user.get("user_id")
        useful_count_flag = redis_conn.get("question_%s_useful_count_%s" % (user_id, id))
        if useful_count_flag:
            return Response({"message": "添加失败...", "success": False})

        try:
            question = self.get_queryset().get(id=id)
        except Exception as e:
            return Response({"message": "查询失败...", "success": False})
        question.useful_count += 1
        if question.unuseful_count != 0:
            question.unuseful_count -= 1
        if question.useful_count >= 10:
            question.solve = 1
        else:
            question.solve = None
        question.save()
        redis_conn.setex("question_%s_useful_count_%s" % (user_id, id), 60 * 10, 1)
        redis_conn.delete("question_%s_unuseful_count_%s" % (user_id, id))


        return Response({"message": "添加成功", "success": True})
        pass

    def update_unuseful_count(self, request, *args, **kwargs):
        """问题有用，修改无用数"""
        id = kwargs.get("id")  # id 表示问题外键的id
        token = request.META.get("HTTP_AUTHORIZATION")[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user.get("user_id")

        redis_conn = get_redis_connection("question")
        question_unuseful_count_flag = redis_conn.get("question_%s_unuseful_count_%s" % (user_id, id))
        if question_unuseful_count_flag:
            return Response({"message": "添加失败...", "success": False})
        try:
            question = self.get_queryset().get(id=id)
        except Exception as e:
            return Response({"message": "查询失败...", "success": False})

        question.unuseful_count += 1
        if question.useful_count != 0:
            question.useful_count -= 1
        question.save()

        redis_conn.setex("question_%s_unuseful_count_%s" % (user_id, id), 60 * 10, 1)
        redis_conn.delete("question_%s_useful_count_%s" % (user_id, id))

        return Response({"message": "添加成功", "success": True})
        pass


class ReplyViewSet(ModelViewSet):
    """评论"""
    queryset = Reply.objects.all()
    serializer_class = ReplySerializer

    def create(self, request, *args, **kwargs):
        """回答"""
        token = request.META.get("HTTP_AUTHORIZATION")[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user.get("user_id")

        content = request.data.get("content")
        parent = request.data.get("parent")
        problem = request.data.get("problem")
        type = request.data.get("type")

        if not all([user_id, content, problem]):
            return Response({"message": "缺少必要参数", "success": False})

        if type not in [0, 1, 2]:
            return Response({"message": "参数有误", "success": False})

        try:
            question = Question.objects.get(id=problem)
        except Exception as e:
            return Response({"message": "问题不存在", "success": False})
        try:
            Reply.objects.create(content=content, parent_id=parent, problem_id=problem, type=type, user_id=user_id)
            question.reply += 1
            question.save()
        except Exception as e:
            print(e)
            return Response({"message": "保存失败", "success": False})

        return Response({"message": "评论成功", "success": True})

    def update_useful_count(self, request, *args, **kwargs):
        """评论有用"""
        id = kwargs.get("id")  # id 表示问题外键的id
        token = request.META.get("HTTP_AUTHORIZATION")[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user.get("user_id")

        redis_conn = get_redis_connection("question")
        reply_useful_count_flag = redis_conn.get("reply_%s_useful_count_%s" % (user_id, id))

        if reply_useful_count_flag:
            return Response({"message": "添加失败...", "success": False})

        try:
            reply = self.get_queryset().get(id=id)
        except Exception as e:
            return Response({"message": "查询失败...", "success": False})
        reply.useful_count += 1
        if reply.unuseful_count != 0:
            reply.unuseful_count -= 1
        reply.save()
        redis_conn.setex("reply_%s_useful_count_%s" % (user_id, id), 60 * 10, 1)
        redis_conn.delete("reply_%s_unuseful_count_%s" % (user_id, id))

        return Response({"message": "添加成功", "success": True})

    def update_unuseful_count(self, request, *args, **kwargs):
        """评论无用"""
        id = kwargs.get("id")  # id 表示问题外键的id
        token = request.META.get("HTTP_AUTHORIZATION")[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user.get("user_id")

        redis_conn = get_redis_connection("question")
        reply_useful_count_flag = redis_conn.get("reply_%s_unuseful_count_%s" % (user_id, id))

        if reply_useful_count_flag:
            return Response({"message": "添加失败...", "success": False})

        try:
            reply = self.get_queryset().get(id=id)
        except Exception as e:
            return Response({"message": "查询失败...", "success": False})
        reply.unuseful_count += 1
        if reply.useful_count != 0:
            reply.useful_count -= 1
        reply.save()
        redis_conn.setex("reply_%s_unuseful_count_%s" % (user_id, id), 60 * 10, 1)
        redis_conn.delete("reply_%s_useful_count_%s" % (user_id, id))

        return Response({"message": "添加成功", "success": True})
        pass






















